package com.laogao.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.laogao.common.page.PageResult;
import com.laogao.entity.TDocument;
import com.laogao.exception.AdxException;
import com.laogao.mapper.DocumentMapper;
import com.laogao.service.AdxDocumentService;
import com.laogao.service.SysFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * @author gao liang
 * @date 2023-03-07 09:52
 */
@Service
@Transactional(rollbackFor = AdxException.class)
public class DocumentServiceImpl implements AdxDocumentService {
    private static final Logger log = LoggerFactory.getLogger(DocumentServiceImpl.class);

    public DocumentServiceImpl(DocumentMapper documentMapper, SysFileService sysFileService) {
        this.documentMapper = documentMapper;
        this.sysFileService = sysFileService;
    }

    private DocumentMapper documentMapper;
    private SysFileService sysFileService;


    @Value("${fileConfig.uploadPath}")
    private String uploadPath;


    @Override
    public TDocument query(Long id) {
        TDocument tDocument = documentMapper.selectById(id);
        return tDocument;
    }

    @Override
    public void delete(Long id) {
        TDocument tDocument = documentMapper.selectById(id);
        if (ObjectUtils.isEmpty(tDocument)) {
            throw new AdxException("文件不存在");
        }
        documentMapper.deleteById(id);

        //删除服务器文件
        ///fileDir/2023/04/12/1681282497004ad7e8088-0c29-411a-915c-b6dbf9ee705d.pptx
        String filePath = tDocument.getSystemPath();
        log.info("服务器文件绝对地址:{}", filePath);
        File file = new File(filePath);
        FileUtil.del(file);
    }

    @Override
    public PageResult<TDocument> getPage(Integer currentPage, Integer pageSize, Integer type, String fileName) throws AdxException {
        IPage<TDocument> pages = new Page<>(currentPage, pageSize);
        if (StringUtils.isEmpty(type)) {
            throw new AdxException("type为空");
        }
        LambdaQueryWrapper<TDocument> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TDocument::getFileType, type);
        if (!StringUtils.isEmpty(fileName)) {
            wrapper.like(TDocument::getFileName, fileName);
        }
        IPage<TDocument> page = documentMapper.selectPage(pages, wrapper);
        return new PageResult(page.getRecords(), pages.getTotal());
    }


    @Override
    public void update(Long id, MultipartFile file, HttpServletRequest request) throws Exception {
        TDocument tDocument = documentMapper.selectById(id);
        if (tDocument == null) {
            throw new AdxException(id + "数据不存在");
        }
        //重新上传文件
        if (file != null) {
            String oldFilePath = tDocument.getSystemPath();
            File oldFile = new File(oldFilePath);
            if (!oldFile.exists()) {
                log.info("oldFilePath:{}", oldFilePath);
                throw new AdxException("文件不存在!");
            }
            //删除原有文件
            FileUtil.del(oldFile);
            //新存入数据
            HashMap<String, Object> hashMap = sysFileService.uploadFileOriginalName(file, request);
            tDocument.setFileName((String) hashMap.get("fileName"));
            tDocument.setFileType((Integer) hashMap.get("fileType"));
            tDocument.setAddress((String) hashMap.get("address"));
            tDocument.setSystemPath((String) hashMap.get("systemPath"));
            documentMapper.updateById(tDocument);
        }
    }

    @Override
    public void add(MultipartFile file, HttpServletRequest request) throws Exception {
        if (ObjectUtils.isEmpty(file)) {
            throw new AdxException("未选择上传文件!");
        }
        LambdaQueryWrapper<TDocument> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TDocument::getFileName, file.getOriginalFilename());
        List<TDocument> res = documentMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(res)) {
            throw new AdxException("文件已存在!");
        }
        TDocument tDocument = new TDocument();
        //重新上传文件
        HashMap<String, Object> hashMap = sysFileService.uploadFileOriginalName(file, request);
        tDocument.setFileName((String) hashMap.get("fileName"));
        tDocument.setFileType((Integer) hashMap.get("fileType"));
        tDocument.setAddress((String) hashMap.get("address"));
        tDocument.setSystemPath((String) hashMap.get("systemPath"));
        documentMapper.insert(tDocument);
    }

}
